package com.suzhouhe.util.response;

import com.suzhouhe.util.constans.ConfigConst;
import com.suzhouhe.util.utils.JsonUtil;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

import javax.servlet.http.HttpServletRequest;
import java.util.Objects;

/**
 * 结果处理
 *
 * @author suzhouhe
 * @date 2020-11-03 17:00
 **/
@ControllerAdvice
public class ResponseAdvice implements ResponseBodyAdvice<Object> {

    @Override
    public boolean supports(MethodParameter methodParameter, Class aClass) {
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        if (requestAttributes == null) {
            return false;
        }
        HttpServletRequest request = requestAttributes.getRequest();
        Object attribute = request.getAttribute(ConfigConst.RESPONSE_RESULT);
        if (attribute == null) {
            return false;
        }
        return (boolean) attribute;
    }

    @Override
    public Object beforeBodyWrite(Object o, MethodParameter methodParameter, MediaType mediaType, Class aClass,
                                  ServerHttpRequest serverHttpRequest, ServerHttpResponse serverHttpResponse) {
        if (Objects.isNull(o)) {
            o = new Result<>().success();
        } else if (o instanceof String) {
            o = JsonUtil.beanToStr(new Result<>().success(o));
        } else if (!(o instanceof Result)) {
            o = new Result<>().success(o);
        }
        return o;
    }
}
